package com.lianqi.emcpframework.data.masker;

import com.lianqi.emcpframework.data.masker.annotation.MaskData;
import com.lianqi.emcpframework.data.masker.stratgey.*;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @program emcp-framework
 * @ClassName StringMasker
 * @description: 字符串脱敏实现类
 * @author: sky
 * @create: 2019/05/26 18:14
 */
public class StringMasker implements MaskerDefinition<String> {

    private static Map<MaskFieldType, DataMaskStrategy<String>> strategyMap = new HashMap<>();

    static {
        strategyMap.put(MaskFieldType.CHINESE_NAME, new ChineseNameMaskStrategy());
        strategyMap.put(MaskFieldType.MOBILE_PHONE, new MobilePhoneMaskStrategy());
        strategyMap.put(MaskFieldType.ID_CARD, new IdCardMaskStrategy());
        strategyMap.put(MaskFieldType.ADDRESS, new AddressMaskStrategy());
        strategyMap.put(MaskFieldType.BANK_CARD, new BankCardMaskStrategy());
        strategyMap.put(MaskFieldType.EMAIL, new EmailMaskStrategy());
        strategyMap.put(MaskFieldType.FIXED_PHONE, new FixePhoneMaskStrategy());
        strategyMap.put(MaskFieldType.PASSWORD, new PasswordStrategy());
        strategyMap.put(MaskFieldType.MONEY, new MoneyStrategy());
        strategyMap.put(MaskFieldType.TO_NULL, new ToNullStrategy());
    }


    @Override
    public boolean support(Field field) {
        MaskData ann = field.getAnnotation(MaskData.class);
        return ann != null && field.getType() == String.class;
    }

    @Override
    public String maskValue(Field field, Object source) {
        MaskData ann = field.getAnnotation(MaskData.class);
        MaskFieldType type = ann.masker();
        DataMaskStrategy<String> strategy = strategyMap.get(type);
        if (strategy == null) {
            throw new RuntimeException("can not find dataMaskStrategy by MaskFieldType:" + type.toString());
        }
        Object old = null;
        try {
            field.setAccessible(true);
            old = field.get(source);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return strategy.maskValue(old, ann);
    }

    @Override
    public DataMaskStrategy getStrategy(MaskFieldType type) {
        return strategyMap.get(type);
    }

    @Override
    public void addDataMaskStrategy(MaskFieldType type, DataMaskStrategy<String> strategy) {
        strategyMap.put(type, strategy);
    }
}
